/*
 *  Copyright 2011 yura.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.vcforms.bean.db;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.opu.vcforms.bean.Template;
import org.opu.vcforms.bean.model.ComboBoxModel;
import org.opu.vcforms.bean.model.DoubleListModel;
import org.opu.vcforms.bean.model.Facultie;
import org.opu.vcforms.datasource.DbManager;
import org.opu.vcforms.datasource.DbQueryHandler;
import org.opu.vcforms.io.Logger;
import org.opu.vcforms.resource.ResourceHandle;

/**
 *
 * @author yura
 */
public class DataInjector {
    public static final String QUERYS_PATH = "/org/opu/vcforms/bean/db/qurys.properties";
    private static final Properties querys;

    static {
        querys = ResourceHandle.loadProperties(null, QUERYS_PATH);
    }

    public static final String FACULTETS = "Facultets";
    public static final String FACULTETS_NUMBER = "Facultets.kod";
    public static final String FACULTETS_NAME = "Facultets.name";

    public static final String GROUPS = "Groups";
    public static final String GROUPS_NAME = "Groups.name";

    public static final String TEMPLATES = "Templats";
    public static final String TEMPLATES_NAME = "Templats.name";
    public static final String TEMPLATES_DATA = "Templats.data";

    public static final String STUDENTS = "Students";

    private DbManager dbManager;

    /**
     *
     * @param dbManager Database manager to send query and
     *  procesed answere
     */
    public DataInjector(DbManager dbManager) {
        this.dbManager = dbManager;
    }

    /**
     *  Return available courses
     * @return available courses
     */
    public ComboBoxModel<Integer> getCourses() {
        ArrayList<Integer> data = new ArrayList<Integer>(6);
        data.add(1);
        data.add(2);
        data.add(3);
        data.add(4);
        data.add(5);
        data.add(6);
        return new ComboBoxModel<Integer>(data);
    }

    /**
     *  Return available semestrs
     * @return available semestrs
     */
    public ComboBoxModel<Integer> getSemestrs() {
        ArrayList<Integer> data = new ArrayList<Integer>(2);
        data.add(1);
        data.add(2);
        return new ComboBoxModel<Integer>(data);
    }

    /**
     *  Return all available facultie in database
     * @return all available facultie in database
     */
    public ComboBoxModel<Facultie> getFaculties() {
        if (dbManager == null){
            return new ComboBoxModel<Facultie>(null);
        } else {
            // TODO: Create DAO with for Facultie {
            DbQueryHandler handler = new DbQueryHandler(dbManager);
            String query = querys.getProperty(FACULTETS);
            String numProp = querys.getProperty(FACULTETS_NUMBER);
            String nameProp = querys.getProperty(FACULTETS_NAME);
            List<String> list = Arrays.asList(numProp, nameProp);

            Logger.debug("Get faculties by query: " + query);
            
            Set<Map> set = handler.get( query, list);

            if (set.isEmpty()){
                Logger.error("Can't get facultets");
                return new ComboBoxModel<Facultie>(null);
            }

            List<Facultie> faculties = new ArrayList<Facultie>(set.size());
            for (Map map : set) {
                int num = (Integer) map.get(numProp);
                String name = (String) map.get(nameProp);

                faculties.add(new Facultie(num, name));
            }

            Logger.debug("The result is: " + faculties);
            // }

            return new ComboBoxModel<Facultie>(faculties);
        }
    }

    /**
     *  Return all groups by facultie and course.
     * @see #getGroups(int, int)
     * @param fac facultie
     * @param course course
     * @return all groups by facultie and course.
     */
    public DoubleListModel getGroups(Facultie fac, Integer course) {
        if (fac == null || course == null){
            return new DoubleListModel(null, null);
        }

        return getGroups(fac.getNumber(), course);
    }

    /**
     *  Return all groups by facultie and course.
     * @see #getGroups(Facultie, int)
     * @param facName facultie number
     * @param course course
     * @return all groups by facultie and course.
     */
    public DoubleListModel getGroups(int facId, int course) {
        if (dbManager == null){
            return new DoubleListModel(null, null);
        } else {
            // TODO: Create DAO with for Groups {
            DbQueryHandler handler = new DbQueryHandler(dbManager);
            String name = querys.getProperty(GROUPS_NAME);
            String query = querys.getProperty(GROUPS);
            
            query = MessageFormat.format(query, screeningValue(facId),
                    screeningValue(course));

            Logger.debug("Get groups by query: " + query);

            Set<Map> set = handler.get(query, Arrays.asList(name));
            if (set.isEmpty()){
                Logger.error("Can't get groups");
                return new DoubleListModel(null, null);
            }

            List<String> all = new LinkedList<String>();
            for (Map map : set) {
                all.add(String.valueOf(map.get(name)));
            }

            Logger.debug("The result is: " + all);
            // }

            return new DoubleListModel(all, null);
        }
    }

    public ComboBoxModel<Template> getTemplates() {
        if (dbManager == null){
            return new ComboBoxModel<Template>(null);
        } else {
            // TODO: Create DAO with for Groups {
            DbQueryHandler handler = new DbQueryHandler(dbManager);
            String query = querys.getProperty(TEMPLATES);
            String nameProp = querys.getProperty(TEMPLATES_NAME);
            String dataProp = querys.getProperty(TEMPLATES_DATA);
            List<String> list = Arrays.asList(dataProp, nameProp);

            Logger.debug("Get groups by query: " + query);

            Set<Map> set = handler.get( query, list);

            if (set.isEmpty()){
                Logger.error("Can't get templates");
                return new ComboBoxModel<Template>(null);
            }

            List<Template> faculties = new ArrayList<Template>(set.size());
            for (Map map : set) {
                String name = (String) map.get(nameProp);
                byte[] data = (byte[]) map.get(dataProp);

                faculties.add(new Template(name, data));
            }

            Logger.debug("The result is: " + faculties);
            //}

            return new ComboBoxModel<Template>(faculties);
        }
    }

    public DbManager getDbManager() {
        return dbManager;
    }

    public void setDbManager(DbManager dbManager) {
        this.dbManager = dbManager;
    }

    public static String screeningValue(Object obj){
        return '\'' + String.valueOf(obj) + '\'';
    }

}
